const express=require('express');
const cookieParser=require('cookie-parser');
const cookieSesson=require('cookie-session');
const bodyParser=require('body-parser');
const multer=require('multer');
const consolidate=require('consolidate');
const jade=require('jade');
const ejs=require('ejs');
const mysql=require('mysql');

var server=express();
server.listen(11111);

//1.解析cookie
server.use(cookieParser('yexuan_cookie'));

//2.使用sesson
var arr=[];
for(var i=0;i<100000;i++){
    arr.push('keys_'+Math.random());
}
server.use(cookieSesson({name:'yexuan_sesson',keys:arr,maxAge:20*60*1000}));

//3.post数据,两种方法各自解析不同类型数据
server.use(bodyParser.urlencoded({extended:false}));
server.use(multer({dest:"./www/upload"}).any());

//用户请求
server.use('/',function(req,res,next){
   //console.log(req.query,req.body,req.cookies,req.session);
   next();
});
//配置模板引擎  
server.set('view engine','html');           //指定哪种模板引擎
server.set('views','./views');              //指定模板引擎放在哪儿
server.engine('html',consolidate.ejs);      //指定哪种模板引擎

server.get('/index',function(req,res){
    if(req.session.userid){     //登录过
       res.render('index.ejs',{name:'yexuan'});      
    }else{                      //没登陆
       res.render('login.ejs',{});
    }
});
server.use('/login',function(req,res){
    var user=req.query.user;
    var pass=req.query.pass;

    //调用数据库查询
    var db=mysql.createConnection({
        host:'localhost',
        user:'root',
        password:'yexuan0628',
        database:'node_js'
    });
    var sql="select * from users where username='"+user+"'";
    db.query(sql,(err,data)=>{
        if(err)
            console.log("出错了",err);
        else{
            console.log("成功了");
            var resault=data;       //数据库得到的为一个数组
            console.log(resault);
            if(resault.length==0){
                res.send("账号或者密码错误...").end();
            }else{
                if(user==resault[0].username&&pass==resault[0].password){
                    res.render('index.ejs',{name:user});  
                }else{
                   // res.send("error");
                   res.redirect('./WWW/404/index.html?id='+resault[0].id);
                   //res.status(404).send("404 error....").end();
                } 
            }                      
        }
    });
});
server.use('/test',function(reqs,res){
    res.redirect('./WWW/test.html');
})

//4.static数据
server.use(express.static(__dirname));

